# -*- coding:utf-8 -*-
import datetime, time, urllib, urllib2
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import pysvn
import locale
import pymongo


#设置编码，否则会出现如下错误：
#pysvn._pysvn_2_7.ClientError: Can't convert string from 'UTF-8' to native encoding:
def setlocale():
	language_code, encoding = locale.getdefaultlocale()
	if language_code is None:
		language_code = 'en_GB'
	if encoding is None:
		encoding = 'UTF-8'
	if encoding.lower() == 'utf':
		encoding = 'UTF-8'

	locale.setlocale( locale.LC_ALL, '%s.%s' % (language_code, encoding))

#svn update
def svnupdate(path):
	client = pysvn.Client()
	ret = client.update(path)
	print ret
	return ret

#svn info
def svninfo(path):
	client = pysvn.Client()
	entry = client.info(path)
	print u"版本号：%s" % entry.commit_revision.number
	print u"提交者：%s" % entry.commit_author
	print u"更新日期：%s" % str(datetime.datetime.fromtimestamp(entry.commit_time))[:-7]
	return entry

#svn变更文件
def svnchanges(work_path):
	ret = {}
	client = pysvn.Client()
	entry = client.info(work_path)

	old_rev = entry.revision.number
	revs = client.update(work_path)
	#print revs
	new_rev = revs[-1].number
	#print 'updated from %s to %s.\n' % (old_rev, new_rev)
	ret['old_rev'] = old_rev
	ret['new_rev'] = new_rev

	head = pysvn.Revision(pysvn.opt_revision_kind.number, old_rev)
	end = pysvn.Revision(pysvn.opt_revision_kind.number, new_rev)
	summary = client.diff_summarize(work_path, head, work_path, end)
	for info in summary:
		path = info.path
		changedtype = info.summarize_kind
		ret[path] = changedtype
		#print "[%s]\t\t\t\t[%s]" % (path, info.summarize_kind)

	#print ret
	return ret

#发送RTX消息，以GET方式提交（内容长度有限制）
def sendrtxmessage(rtxserver, receiver, title, content):
	url = "http://%s:8012/sendnotify.cgi?receiver=%s&title=%s&msg=%s" % (rtxserver, receiver, title, content)
	#if sys.platform == "win32":
	url = url.encode('gbk')	#url.decode('utf8').
	urllib.urlopen(url)

#发送RTX消息，以POST方式提交
def sendrtxmessage2(rtxserver, receiver, title, content):
	url = "http://%s:8012/sendnotify.cgi" % rtxserver
	values = {'receiver' : receiver.encode('gbk'), 'title' : title.encode('gbk'), 'msg' : content.encode('gbk')}
	url = url.encode('gbk')

	data = urllib.urlencode(values)
	req = urllib2.Request(url, data)
	response = urllib2.urlopen(req)
	ret = response.read()
	print ret

#发送邮件
def sendmail(mail_host, mail_user, mail_pass, to_user, subject, content, mail_postfix = "qq.com"):
	#设置服务器，用户名、口令以及邮箱的后缀
	me = mail_user + "<" + mail_user + "@" + mail_postfix + ">"
	maicontent = MIMEText(content)
	maicontent['Subject'] = subject
	maicontent['From'] = me
	maicontent['To'] = to_user

	try:
		s = smtplib.SMTP()
		s.connect(mail_host)
		s.login(mail_user, mail_pass)
		s.sendmail(me, to_user, maicontent.as_string())
		s.close()
		return True
	except Exception, e:
		print str(e)
		return False

#发送邮件，对于Exchange邮件服务器，如果要验证发送账户，smtplib库会出错，直接匿名发送得了
def sendmail2(mail_server, mail_sender, address_book, subject, content):
	#address_book, format：['haifeng.zhao@kuen.com', 'kuen@kuen.com']
	msg = MIMEMultipart()
	sender = mail_sender
	content += r'访问 http://192.168.5.2:9999/ 查看更多信息'

	msg['From'] = sender
	msg['To'] = ','.join(address_book)
	msg['Subject'] = subject
	msg.attach(MIMEText(content, 'plain'))
	text = msg.as_string()

	# Send the message via our SMTP server
	s = smtplib.SMTP(mail_server)
	s.sendmail(sender,address_book, text)
	s.quit()        

#检查SVN的更新情况
def project_svn(path, team):
	#pathA = "/data/release/tech"
	project = path['name']
	ret = svnchanges(path['path'])

	old_rev = ret['old_rev']
	new_rev = ret['new_rev']
	del ret['old_rev']
	del ret['new_rev']

	svnupstr =  '「%s」updated from %s to %s.' % (project, old_rev, new_rev)
	print svnupstr
	values	 = {}

	if int(new_rev) > int (old_rev):
		entry = svninfo(path['path'])

		messagea = u"SVN版本号：%s\n" % entry.commit_revision.number
		messagea += u"提交者：%s\n" % entry.commit_author
		messagea += u"更新日期：%s\n\n" % str(datetime.datetime.fromtimestamp(entry.commit_time))[:-7]
		messagea += u"更新内容：\n"

		values['project']	= path['name']
		values['revision']	= entry.commit_revision.number
		values['author']	= entry.commit_author
		values['date']		= str(datetime.datetime.fromtimestamp(entry.commit_time))[:-7]
		values['content']	= ""

		for i in ret:
			values['content']	+= "%s [%s]\n" % (i, ret[i])
			messagea += "%s [%s]\n" % (i, ret[i])

		InsertDB(values)

		#邮件通知开始，必要的时候注释掉
		mail_server = "kuen-mail.kuen.com"
		mail_sender = "kuen_svn@kuen.com"
		address_book = ["meimei.han@kuen.com", "lei.li@kuen.com"]
		subject = u"「%s」的SVN于 %s 更新了，版本号：%s，提交者：%s" % (project.decode('utf8'), str(datetime.datetime.fromtimestamp(entry.commit_time))[:-7], entry.commit_revision.number, entry.commit_author)
		#messagea += u'访问<a href="http://192.168.5.2:9999/"> 查看更多信息</a>'
		sendmail2(mail_server, mail_sender, address_book, subject.encode('utf8'), messagea.encode('utf8'))
		#邮件通知结束，必要的时候注释掉

		for name in team.values():
			sendrtxmessage(u'192.168.100.101', name.decode('utf8'), svnupstr.decode('utf8'), messagea)

#更新记录入库
def InsertDB(values):
	conn = pymongo.Connection('192.168.100.100', 27017)
	svn_db = conn.version_x
	update_record = svn_db.update_record
	update_record.insert(values)


#主函数
if __name__ == "__main__":

	#定义项目路径及团队成员，项目路径为svn checkout出来的一个路径
	Project_X = {'name' : 'X项目', 'path' : '/data/release/Project_X'}
	Team_X = {'meimei.han' : '韩梅梅','lei.li' : '李雷'}

	setlocale()
	
	while True:
		project_svn(Project_X, Team_X)
		time.sleep(30)		#每隔30秒检查一次
